/**
 * 基于Mock.js搭建的自定义mock数据生成服务
 * @type {MockXMLHttpRequest|exports|module.exports}
 */

var Mock = require('mockjs');
var Config = require('./rules/data.rule.config.js');
const Random = Mock.Random;

var MockMethod = {
    textCN: "cparagraph",
    textEN: "paragraph",
    titleEN: "title",
    titleCN: "ctitle",
    nameEN: "name",
    nameCN: "cname",
    stringCN: "csentence",
    stringEN: "string",
    color: "color",
    date: "date",
    uuid: "guid",
    idCard: "id",
    boolean: "boolean",
    number: "natural",
    int: "integer",
    float: "float",
    url: "url",
    domain: "domain",
    email: "email",
    ip: "ip",
    province: "province",
    city: "city",
    county: "county",
    zipCode: "zip"

}

var util = {
    isArray: function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]"
    },

    isObject: function () {
        return Object.prototype.toString.call(arg) === "[object Object]"
    },


    loop: function (data, fun, key = "children") {
        data.map(item=> {
            if (item[key]) {
                fun(item);
                util.loop(item[key], fun)
            } else {
                fun(item);
            }
        })
    },

    defaults: function (key) {
        return Config[key]['template'];
    },

    oneOf: function (pool) {
        if (typeof pool === "string") {
            return pool.charAt(Math.floor(Math.random() * pool.length));
        } else if (util.isArray(pool)) {
            return pool[Math.floor(Math.random() * pool.length)];
        }
    },

    arrayToTree: function (data, pidKey, idKey) {
        //temp 用于存储没有找到父节点的数据
        //tree 用于存储已经遍历完成的树节点数据
        var temp = [],
            tree = [],
            tempNode = {};
        //首先把父节点的数据过滤出来
        data.map(function (item) {
            if (!item[pidKey] || item[pidKey] == item[idKey]) {
                tree.push(item);
            } else {
                temp.push(item);
            }
        })

        //用于在父节点中查找某个key的值为value的节点
        function loopTree(data, key, value) {
            data.map(function (item) {
                if (item[key] == value) {
                    tempNode = item;
                } else if (item.children) {
                    loopTree(item.children, key, value);
                }

            })
            return tempNode;
        }

        //遍历没有归属的节点数据、直到temp数据为空、或者为垃圾数据
        function loop(data) {
            var len = data.length,
                temp = [];
            data.map(function (item, index) {
                var node = loopTree(tree, idKey, item[pidKey]);
                if (node) {
                    node.children = node.children || [];
                    node.children.push(item)
                } else {
                    temp.push(item);
                }
                if (len == (index + 1)) {
                    if (temp.length > 0 && temp.length < len) {
                        loop(temp);
                    }
                }
            })
        }

        loop(temp)

        return tree;
    },

    //生成各种类型的数据
    mockFun: function (nodeConfig) {
        let {type,len,format,prefix,pool,one}=nodeConfig;
        type = MockMethod[type] || type;

        if (len) {
            return Random[type](len[0], len[1]);
        }
        if (format) {
            return Random[type](format);
        }
        if (prefix) {
            return Random[type](prefix);
        }
        if (one) {
            return util.oneOf(one);
        }
        if (pool) {
            return Random[type](pool);
        }
        return Random[type]();
    },

    /**
     * 根据模板生成数据对象
     * demo:表示一个有三个孩子的人
     * {
     *  name:{
     *      type:"nameCN"
     *  },
     *  children#list-3#child:[{
     *      name:{
     *          type:"nameCN"
     *      }
     *  }]
     * }
     * @param node
     * @returns {{}}
     */
    node: function (node) {
        var childReg = /#child$/;
        var lenReg = /#list-([1-9][0-9]{0,1})/;
        var randomReg = /#rlist-([1-9][0-9]{0,1})/;
        var data = {};
        for (var p in node) {
            var lens=lenReg.exec(p);
            var random=randomReg.exec(p);
            var len=lens?lens[1]:0;
            random=random?random[1]:0;
            var key=p.replace(childReg, "").replace(lenReg,'').replace(randomReg,'');
            if (childReg.test(p)) {
                var temp = node[p];
                if (util.isArray(temp)) {
                    data[key] = [];
                    temp.map(item=> {
                        data[key].push(util.node(item));
                    })
                } else {
                    if(len>0){
                        data[key]=[];
                        for(let i=0;i<len;i++){
                            data[key].push(util.node(temp));
                        }
                    }else{
                        if(random>1){
                            data[key]=[];
                            random=Random.natural(1, random);
                            for(let i=0;i<random;i++){
                                data[key].push(util.node(temp));
                            }
                        }else{
                            data[key]=util.node(temp);
                        }
                    }
                }
            } else {
                if(len>0){
                    data[key]=[];
                    for(let i=0;i<len;i++){
                        data[key].push(this.mockFun(node[p]));
                    }
                }else{
                    data[p]= this.mockFun(node[p])
                }
                 ;
            }
        }
        return data;
    },

    randomNode(rule){

    }
}

module.exports = {

    //生成树节点
    tree: function (tree, level = 4) {
        tree = tree || util.defaults("tree");
        tree._$id = {
            type: "uuid"
        };
        var pid = [], trees = [], temp = [];
        for (var i = 0; i < level; i++) {
            var count = Random.natural(3, 5) * (i + 1);
            var pcount = pid.length;
            for (var j = 0; j < count; j++) {
                var node = util.node(tree);
                if (i == 0) {
                    node._$pid = node._$id;
                    pid.push(node._$id);
                } else {
                    node._$pid = pid[(Random.natural(1, pcount) - 1)];
                    temp.push(node._$id);
                }
                trees.push(node);
            }
            if (temp.length > 0) {
                pid = temp.slice(0);
            }
        }

        var result = util.arrayToTree(trees, "_$pid", "_$id");

        //隐藏内部关联关系id
        util.loop(result, item=> {
            delete item._$id;
            delete item._$pid;
        })
        return result;
    },


    defaultData: function ({type,len=10,size='240*120',level=4}) {
        var template = util.defaults(type);
        if (type == "list") {
            var array = [];
            for (var i = 0; i < len; i++) {
                array.push(util.node(template));
            }
            return array;
        } else if(type=="image"){
            return {
                url:Random.image(size.replace("*","x"))
            }
        }else if(type=="tree"){
            return this.tree(template,level)
        }else{
            return util.node(template);
        }
    },


    object: function (item) {
        return util.node(item);
    }

}

